﻿using Communicate;
using OtherDevice.UserDefineCtrl;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace OtherDevice
{
    [Description("基恩士扫码")]
    class Scan_SR700: SNTcpIpBase
    {
        private object obj = new object();
        int n_Length = 0;
        public Scan_SR700(string strName) : base(strName)
        {
            controlFrom = new Form_Scan();
        }
        public override int linkEtherNetControl()
        {
            if (link != null)
            {
                if (link.IsOpen())
                    link.Close();

            }
            link.RecvStringMessageEvent += (object sender, AsyTcpSocketEventArgs e) =>
            {
                if (e.Message != "EXWTRG")
                {
                    InMessageQueue(e.Message);
                }
            };
            if (link.Open())
                return 0;
            else
                return -1;
        }

        public override int Fucntion_获取SN码(int n_SnLength, ref string strSN, int n_Timeout = 2000)
        {
            lock (obj)
            {
                n_Length = n_SnLength;
                clearMessageQueue();
                Send("LON\r");
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                while (true)
                {
                    int ret = OutMessageQueue(out strSN);
                    if (ret == 0)
                    {
                        if (strSN.Contains("ER,LON"))
                            return -1;
                        else
                            return 0;
                    }
                    if (n_Timeout > 0 && stopwatch.ElapsedMilliseconds > n_Timeout)
                    {
                        strSN = "";
                        Send("LOFF\r");
                        return -2;
                    }
                    Thread.Sleep(5);
                }


            }
        }
    }
}
